package xipujewel.xipujewel.web.account;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.esoar.modules.utils.WebUtil;
import net.esoar.modules.web.BaseController;
import net.esoar.modules.web.pojo.JPage;
import net.esoar.modules.web.pojo.WebPojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import xipujewel.xipujewel.entity.account.User;
import xipujewel.xipujewel.entity.app.PriceBaseNumber;
import xipujewel.xipujewel.entity.app.Ring;
import xipujewel.xipujewel.entity.app.RingType;
import xipujewel.xipujewel.service.PriceBaseNumberManager;
import xipujewel.xipujewel.service.RingManager;
import xipujewel.xipujewel.service.RingTypeManager;
import xipujewel.xipujewel.service.account.UserManager;
import xipujewel.xipujewel.utils.FileUtil;
import xipujewel.xipujewel.utils.UserUtil;

/**
 * 
 * @author hang
 *
 */
@Controller
@RequestMapping(value = "/ring")
public class RingController extends BaseController<Ring> {

	@Autowired
	private RingManager ringManager;

	@Autowired
	private UserManager userManager;

	@Autowired
	private RingTypeManager ringTypeManager;

	@Autowired
	private PriceBaseNumberManager priceBaseNumberManager;

	@RequestMapping("")
	public String list(Model model, ServletRequest request) {
		Map<String, Object> searchParams = getFilters(request);
		initOrder("id", JPage.ASC);
		User cUser = userManager.findByLoginNameAndType01(UserUtil.getCurrentUserLoginName());
		List<RingType> ringTypes = ringTypeManager.getAll();
		model.addAttribute("cUser", cUser);
		model.addAttribute("ringTypes", ringTypes);
		model.addAttribute("ringType", (String) searchParams.get("EQ_ringType.id"));
		model.addAttribute("ringBaseNumber", cUser.getPriceBaseNumber().getRingBaseNumber());

		jPage = ringManager.search(searchParams, jPage);
		if (cUser.getType() == 1) {
			for (Ring ring : jPage.getResult()) {
				float secondPrice = ring.getPrice() * cUser.getPriceBaseNumber().getRingBaseNumber();
				ring.setSecondPrice(secondPrice);
			}
		}

		return "ring/ring-list";
	}

	@RequestMapping(value = "input/{id}/{typeId}")
	public String input(@PathVariable(ID) Long id, @PathVariable("typeId") Long typeId, Model model) {
		Ring ring = ringManager.get(id);
		model.addAttribute("typeId", typeId);
		model.addAttribute("ring", ring);
		return "ring/ring-input";
	}

	@RequestMapping(value = DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo delete(@PathVariable(ID) Long id, HttpServletRequest httpRequest) {
		ringManager.delete(id, getServerPath(httpRequest));
		return WebUtil.getNavTabAjaxDone("w_ring");
	}

	@RequestMapping(value = DELETES, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo deletes(@RequestParam(IDS) List<Long> ids, HttpServletRequest httpRequest) {
		for (Long id : ids) {
			ringManager.delete(id, getServerPath(httpRequest));
		}
		return WebUtil.getNavTabAjaxDone("w_ring");
	}

	@RequestMapping(value = "detail/{id}")
	public String input(@PathVariable(ID) Long id, Model model) {
		Ring ring = ringManager.get(id);
		model.addAttribute("ring", ring);
		return "ring/ring-detail";
	}

	@RequestMapping(value = "save", method = RequestMethod.POST, produces = { "text/html" })
	@ResponseBody
	public String upload(MultipartHttpServletRequest request, @Valid @ModelAttribute("ring") Ring ring,
			@RequestParam("typeId") Long typeId) throws IOException {
		Map<String, MultipartFile> fileMap = request.getFileMap();
		RingType ringType = ringTypeManager.get(typeId);
		ring.setRingType(ringType);
		ringManager.save(fileMap, ring, getServerPath(request));
		return WebUtil.getJsonMapper().toJson(WebUtil.getCloseCurrent("w_ring"));
	}

	@RequestMapping(value = "getImage", method = RequestMethod.GET)
	@ResponseBody
	public void getImage(@RequestParam("photo") String photo, HttpServletRequest httpRequest,
			HttpServletResponse response) throws IOException {
		//		HttpHeaders headers = new HttpHeaders();
		//		headers.setContentType(MediaType.IMAGE_JPEG);
		//		headers.setContentDispositionFormData("attachment", "ring.jpg");
		//		return new ResponseEntity<byte[]>(FileUtil.download(this.getServerPath(httpRequest), photo), headers,
		//				HttpStatus.OK);
		response.setContentType("image/*"); // 设置返回的文件类型
		response.setHeader("Content-disposition", "attachment; filename=" + photo);
		OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
		toClient.write(FileUtil.download(this.getServerPath(httpRequest), photo)); // 输出数据
		toClient.close();
	}

	@RequestMapping(value = "setDiscount", method = RequestMethod.GET)
	public String input(Model model) {
		String loginName = UserUtil.getCurrentUserLoginName();
		User user = userManager.findByLoginNameAndType01(loginName);
		PriceBaseNumber priceBaseNumber = user.getPriceBaseNumber();
		model.addAttribute("priceBaseNumber", priceBaseNumber);
		return "ring/discount-input";
	}

	@RequestMapping(value = "saveDiscount")
	@ResponseBody
	public WebPojo saveDiscount(@RequestParam("priceBaseNumberId") Long priceBaseNumberId,
			@RequestParam("discount") float discount) {
		PriceBaseNumber priceBaseNumber = priceBaseNumberManager.get(priceBaseNumberId);
		priceBaseNumber.setRingBaseNumber(discount);
		priceBaseNumberManager.save(priceBaseNumber);
		return WebUtil.getCloseCurrent("w_ring");
	}

	@Override
	public String baseMapping() {
		return null;
	}

	@Override
	public String getModelName() {
		return null;
	}

	@ModelAttribute("ring")
	public Ring getModel(@RequestParam(value = ID, required = false) Long id) {
		if (id != null) {
			return ringManager.get(id);
		}
		return null;
	}

	private String getServerPath(MultipartHttpServletRequest request) {
		return request.getSession().getServletContext().getRealPath("WEB-INF");
	}

	public String getServerPath(HttpServletRequest httpRequest) {
		return httpRequest.getSession().getServletContext().getRealPath("/WEB-INF");
	}

	/*	private String getServerPath(MultipartHttpServletRequest request) {
			return request.getSession().getServletContext().getRealPath("/");
		}

		public String getServerPath(HttpServletRequest httpRequest) {
			return httpRequest.getSession().getServletContext().getRealPath("/");
		}*/

}
